//
//  DeviceSearchViewController.swift
//  TimeBoat
//
//  Created by Jun on 2022/9/5.
//  Copyright © 2022 Time Boat. All rights reserved.
//

import UIKit
import Rswift

@objc class DeviceSearchViewController: BaseViewController {
    @IBOutlet var mSearchAnimationImageView: UIImageView!
    @IBOutlet var mTableView: UITableView!
    private var mDataList: [Any] = [NSObject]()
    private let mCenter = NotificationCenter.default
    private var mHUD: HUD?
    
    @objc static func viewController() -> DeviceSearchViewController {
        return DeviceSearchViewController()
    }
    
    deinit {
        Log.debug("device search view controller deinit")
        
        removeBTLEObserver()
        stopSearch()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "添加设备"
        
        setupView()
        addBTLEObserver()
        startSearch()
    }
    
    private func startSearch() {
        BTLEManager.shared.startSearch()
    }
    
    private func stopSearch() {
        BTLEManager.shared.stopSearch()
    }
    
    private func removeBTLEObserver() {
        Log.debug("remove BTLE observer")
        
        mCenter.removeObserverBTLEDidDiscoverPeripheral(observer: self, object: nil)
        
        mCenter.removeObserverBTLEDidConnectedPeripheral(observer: self, object: nil)
        
        mCenter.removeObserverBTLEDidConnectFailPeripheral(observer: self, object: nil)
    }
    
    private func addBTLEObserver() {
        Log.debug("add BTLE observer")
        
        mCenter.addObserverBTLEDidDiscoverPeripheral(observer: self, selector: #selector(didDiscoverPeripheralHandle), object: nil)
        
        mCenter.addObserverBTLEDidConnectedPeripheral(observer: self, selector: #selector(didConnectedPeripheralHandle), object: nil)
        
        mCenter.addObserverBTLEDidConnectFailPeripheral(observer: self, selector: #selector(didConnectPeripheralFailHandle), object: nil)
    }
    
    @objc func didDiscoverPeripheralHandle() {
        Log.debug("did discover perpheral handle")
        mTableView.reloadData()
    }
    
    @objc func didConnectedPeripheralHandle() {
        mHUD?.hide(animated: false)
        
        HUD.showSuc(msg: "连接成功", delay: 0, in: nil)
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    @objc func didConnectPeripheralFailHandle() {
        mTableView.reloadData()
        mHUD?.hide(animated: false)
        
        HUD.showFail(msg: "连接异常", delay: 0, in: self.view)
        
        startSearch()
    }
    
    @discardableResult
    private func addUserDeivce(item: CBPeripheralItem, completion: APICompletion<NSObject>? = nil) -> APITASK? {
        let token = AccountManager.shareAccount().token()
        if (nil != token) {
            var params = [String: Any]()
            params["token"] = token
            params["name"] = item.name
            params["mac"] = item.macAddress
            return API.POST("device/add", params, completion)
        }
        
        return nil
    }
    
    private func animationSearcchIcon() {
        var images = [UIImage]()
        let arrays = [
            R.image.loading01, R.image.loading02, R.image.loading03, R.image.loading04, R.image.loading05,
            R.image.loading06, R.image.loading07, R.image.loading08, R.image.loading09, R.image.loading10
        ]
        
        for i in arrays {
            images.append(UIImage.init(resource: i)!)
        }
        
        self.mSearchAnimationImageView.animationImages = images.reversed()
        self.mSearchAnimationImageView.animationDuration = 0.8
        self.mSearchAnimationImageView.startAnimating()
    }
    
    private func setupView() {
        animationSearcchIcon()
        mTableView.register(R.nib.searchDeviceCell)
    }
}

// MARK: table view
extension DeviceSearchViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return BTLEManager.shared.mPerpheralList.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: R.reuseIdentifier.searchDeviceCell, for: indexPath)
        let item = BTLEManager.shared.mPerpheralList[indexPath.row]
        cell!.update(title: (item.macAddress ?? "") + "(" + (item.name ?? "") + ")", subTitle: "RSSI: \(item.rssi) dbm")
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return SearchDeviceCell.cellHeight()
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: false)
        
        Log.debug("did select row ")
        
        mHUD = HUD.showLoading(msg: "正在连接...", delay: 0, in: nil)
        
        if (indexPath.row < BTLEManager.shared.mPerpheralList.count) {
            let item = BTLEManager.shared.mPerpheralList[indexPath.row]
            addUserDeivce(item: item) {[weak self] result in
                if (result.suc) {
                    self?.mCenter.postBTLEReloadDeviceList(object: nil)
                    BTLEManager.shared.connectPeripheralItem(item: item)
                } else {
                    self?.mHUD?.hide(animated: false)
                    HUD.showFail(msg: "连接异常", delay: 0, in: nil)
                    self?.mTableView.reloadData()
                }
            }
        }
    }
}

